Set Default Values for Variables in Bash Scripts
This post introduces some useful snippets and grammars in Bash shell for scripting to set default values.
The family consists of various grammars.
${var:-default}- If
varis unset or is an empty string, then returndefault, otherwise unchanged. It does not modify the value ofvar. ${var-default}- Only if
varis unset, then returndefault. Ifvaris an empty string, the final value is still an empty string. It does not modify the value ofvar. ${var:=word}- If
varis unset or empty, setvartoword, and then returnword. ${var:?error_log}- If
varis unset or empty, outputerror_logtostderrand exits the script. ${var:+word}- If
varis set and non-empty, returnword, otherwise return empty string. ${var+word}- If
varis set (even if it’s an empty string), returnword.